'use strict';

const Controller = require('egg').Controller;

class IndexController extends Controller {

  /*
     * 首页
     **/
  async index() {
    const act_list = this.ctx.session.act_list;
    const menu_list = act_list ? await this.ctx.service.admin.getRoluMenu(act_list) : [];
    const data_list = {
      menu_list,
      admin_name: this.ctx.session.admin_name,
      admin_id: this.ctx.session.admin_id,
      host: this.ctx.request.host,
    };
    await this.ctx.render(this.ctx.view_path(), data_list);
  }

  /*
     * 网站地图
     **/
  async map() {
    const all_menu = await this.ctx.service.admin.getRoluMenu('all');
    await this.ctx.render(this.ctx.view_path(), { all_menu });
  }

  /*
     * 登录页
     **/
  async login() {
    const ctx = this.ctx;
    const admin_id = ctx.session.admin_id;
    if (admin_id) {
      await ctx.redirect(ctx.helper.pathFor('adinin'));
    }
    const method = ctx.request.method;
    if (method === 'POST') {
      const username = ctx.request.body.username;
      const password = ctx.request.body.password;
      const vertify = ctx.request.body.vertify;
      let body = { status: 0, message: '帐号或密码错误' };
      const captcha = ctx.session.captcha;
      if (captcha && vertify && vertify.toLowerCase() === captcha.toLowerCase()) {
        if (ctx.helper.check_name(username)) {
          const admin = await ctx.model.Admin.find({ where: { user_name: username }, raw: true });
          if (admin) {
            if (admin.password === ctx.helper.md5(ctx.helper.md5(password))) {
              const role_info = await ctx.service.admin.getAdminRule(admin.role_id);
              if (role_info && role_info.act_list) {
                await ctx.service.admin.loginRecord(admin.admin_id);
                ctx.session.admin_id = admin.admin_id;
                ctx.session.admin_name = admin.user_name;
                ctx.session.act_list = role_info.act_list;
                body = { status: 1, message: '登录成功' };
              } else {
                body.message = '帐号已冻结';
              }
            }
          }
        }
      } else {
        body.message = '验证码错误';
      }
      ctx.session.captcha = null;
      ctx.body = body;
      ctx.status = 200;
    } else {
      await ctx.render(ctx.view_path());
    }
  }

  async logout() {
    const admin_id = this.ctx.session.admin_id;
    if (admin_id) {
      this.ctx.session.admin_id = null;
      this.ctx.session.admin_name = null;
      this.ctx.session.act_list = null;
    }
    this.ctx.redirect(this.ctx.helper.pathFor('adinlo'));
  }

  /*
       * 消息管理
       **/
  async message() {
    const data_list = {
      host: this.ctx.request.host,
    };
    await this.ctx.render(this.ctx.view_path(), data_list);
  }
}

module.exports = IndexController;
